import {
    createRouter,
    createWebHistory
} from 'vue-router';
import {
    useAuthStore
} from '../store/index.js';

const routes = [{
        path: '/',
        component: () => import('../views/layout/index.vue'),
        redirect: to => ({
            path: '/home'
        }),
        meta: {
            requiresAuth: true
        },
        children: [{
                path: 'home',
                name: 'Home',
                component: () => import('../views/home/index.vue'),
                meta: {
                    title: '首页'
                }
            },
            {
                path: 'ammg',
                name: 'Ammg',
                component: () => import('../views/ammanagement/index.vue'),
                meta: {
                    title: '广告管理'
                }
            },
            {
                path: 'about',
                name: 'About',
                component: () => import('../views/about/index.vue'),
                meta: {
                    title: '关于'
                }
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login/login.vue'),
        meta: {
            requiresAuth: false
        }
    },{
        path: '/fd',
        name: 'FD',
        component: () => import('../views/frontdesk/index.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, form) => {
    let token = useAuthStore().token || localStorage.getItem('token')
    if (to.name != 'Login' && !token) {
        return {
            name: 'Login'
        }
    }
})

router.beforeEach((to, form) => {
    let token = useAuthStore().token || localStorage.getItem('token')
    if (to.name == 'Login' && token) {
        return {
            name: 'Home'
        }
    }
})

export default router